package cn.yshujia.controller;

import cn.yshujia.constant.SystemConst;
import cn.yshujia.domain.dto.PageDTO;
import cn.yshujia.domain.entity.Router;
import cn.yshujia.domain.vo.ApiVO;
import cn.yshujia.domain.vo.PageVO;
import cn.yshujia.domain.vo.RouterVO;
import cn.yshujia.service.impl.RouterServiceImpl;
import cn.yshujia.utils.JwtTokenUtils;
import cn.yshujia.utils.StringUtils;
import com.alibaba.fastjson2.JSON;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author YShuJia
 * @create 2024/4/23
 * @description 控制器
 */

@RestController
@Tag (name = "Router", description = "路由Api")
public class RouterController {
	
	@Resource
	RouterServiceImpl service;
	
	@GetMapping ("/router/list")
	@Operation (summary = "根据用户携带 Token 获取路由")
	public ApiVO<List<RouterVO>> defaultList(HttpServletRequest request) {
		String token = request.getHeader(SystemConst.TOKEN_KEY);
		
		if (StringUtils.isEmpty(token)) {
			return ApiVO.success(service.getList());
		}
		// 获取用户ID
		Long userId = JwtTokenUtils.getUserId(token);
		return ApiVO.success(service.getList(userId));
	}
	
	@GetMapping ("/admin/router/page")
	@Operation (summary = "Admin 获取权限内路由")
	@PreAuthorize ("@sys.hasOnePermission('router:all')")
	public ApiVO<PageVO<RouterVO>> allList(@RequestParam String dto) {
		PageDTO pageDTO = JSON.parseObject(dto, PageDTO.class);
		if (null == pageDTO) {
			return ApiVO.error();
		}
		return ApiVO.success(service.getAdminPage(pageDTO));
	}
	
	@GetMapping ("/admin/router/level/{isAdmin}")
	@Operation (summary = "Admin 获取一级路由做下拉框数据")
	@PreAuthorize ("@sys.hasOnePermission('router:all')")
	public ApiVO<List<Router>> level(@PathVariable Boolean isAdmin) {
		return ApiVO.success(service.getOneLevelByIsAdmin(isAdmin));
	}
	
	@PostMapping ("/admin/router/insert")
	@Operation (summary = "admin 添加路由")
	@PreAuthorize ("@sys.hasOnePermission('router:all')")
	public ApiVO<Boolean> add(@RequestBody Router router) {
		boolean bool = service.insert(router);
		if (bool) {
			return ApiVO.success(true);
		}
		return ApiVO.error();
	}
	
	@PutMapping ("/admin/router/update")
	@Operation (summary = "admin 更新路由")
	@PreAuthorize ("@sys.hasOnePermission('router:all')")
	public ApiVO<Boolean> edit(@RequestBody Router router) {
		boolean result = service.update(router);
		if (result) {
			return ApiVO.success(true);
		}
		return ApiVO.error();
	}
	
	
	@DeleteMapping ("/admin/router/delete")
	@Operation (summary = "admin 删除路由")
	@PreAuthorize ("@sys.hasOnePermission('router:all')")
	public ApiVO<Boolean> remove(@RequestBody List<Long> ids) {
		boolean result = service.remove(ids);
		if (result) {
			return ApiVO.success(true);
		}
		return ApiVO.error();
	}
}


